<?php

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!isset($_SESSION['a_group'])
    ||  $_SESSION['a_group'] != 1 && ($_SESSION['a_id'] != $id || $id < 1)
) {

    Js::alert(fl('err_access'));
    exit;
}

if (Http::isPost()) {

    if (isset($_SESSION['a_group']) && 1 == $_SESSION['a_group']) {
        $us_username = Form::input('us_username', '>2');
        $us_enable = Form::input('us_enable', '0');
        $us_e2group = Form::input('us_e2group', '>>0');
        $us_onlinecount = intval(Form::input('us_onlinecount', '0'));
        $us_email = Form::input('us_email', '@');
    } else {
        $us_username = $_SESSION['a_username'];
        $us_enable = $_SESSION['a_access'];
        $us_e2group = $_SESSION['a_group'];
        $us_onlinecount = $_SESSION['onlinecount'];
        $us_email = $_SESSION['a_email'];
    }

    $us_password = Form::input('us_password');
    $us_password_confirm = Form::input('us_password_confirm');
    $us_fullname = Form::input('us_fullname', 'ne');
    $us_address = Form::input('us_address', 'ne');
    $us_phone = Form::input('us_phone', 'ne');
    $us_website = Form::input('us_website', 'ne');

    if (0 === $id || (!empty ($us_password) || !empty($us_password_confirm))) {

        if ($us_password !== $us_password_confirm) {
            $GLOBALS['err_us_password'] .= '<br />' .  fl('password_not_match');
            $GLOBALS['err_us_password_confirm'] .= '<br />' .  fl('password_not_match');
            $GLOBALS['formErrors'][] = 'us_password';
            $GLOBALS['formErrors'][] = 'us_password_confirm';
        } elseif (strlen($us_password) < 6 || strlen($us_password_confirm) < 6) {
            $GLOBALS['err_us_password'] .= '<br />' . fl('err_longer', 5);
            $GLOBALS['err_us_password_confirm'] .= '<br />' . fl('err_longer', 5);
            $GLOBALS['formErrors'][] = 'us_password';
            $GLOBALS['formErrors'][] = 'us_password_password';
        }
    }

    // check if the username is existing
    if (empty($GLOBALS['err_us_username']) && Db::getOneRow('useradminid', 'useradmin'
        , "us_username = '" . mysql_escape_string($us_username) . "' AND useradminid <> $id")) {
        $GLOBALS['err_us_username'] .= '<br />' . fl('user_existing');
        $GLOBALS['formErrors'][] = 'us_username';
    }

    // check if the email is existing
    if (empty($GLOBALS['err_us_email']) && Db::getOneRow('useradminid', 'useradmin'
        , "us_email = '" . mysql_escape_string($us_email) . "' AND useradminid <> $id")) {
        $GLOBALS['err_us_email'] .= '<br />' . fl('email_existing');
        $GLOBALS['formErrors'][] = 'us_email';
    }

    if (Form::isValid()) {

        $ignoredFields = array('useradminid'
            , 'us_createtime'
            , 'us_lastonline'
            , 'us_lastip'
            , 'us_pass_code'
            , 'us_pass_reqtime');

        // update password when it has been changed and passed all validators
        if ($id > 0 && empty($us_password)) {
            $ignoredFields[] = 'us_password';
        } else {
            $us_password = md5($us_password);
        }

        eval(Db::update('useradmin', 'useradminid = ' . $id, $ignoredFields));
        Js::alert(fl('success_update'));
        _goHome();
    }

} else {

    if ($id > 0) {
        // check if root admin wants to delete this user
        if (isset($_GET['del'])
            && isset($_SESSION['a_group']) && 1 == $_SESSION['a_group']) {

            $username = mysql_escape_string($_GET['del']);

            Db::delete('useradmin', "us_username = '$username'");
            /**
             * @todo delete all entries posted by this user
             */
            Js::alert(fl('user_deleted'));
            _goHome();
        }

        $row = Db::getOneRow('*', 'useradmin', 'useradminid = ' . $id);

        if (!$row) {
            Js::alert(fl('user_not_exist'));
            _goHome();
        }

        $logs = db()->getAll("SELECT * FROM useradminlog WHERE lg_user = '" . mysql_escape_string($row['us_username']) . "' ORDER BY lg_time DESC LIMIT 25");

        $view_log = '';
        foreach ($logs as $logrow)
        {
            $view_log .= date("H:i - m/d/y",Date::toLocalTime($logrow['lg_time'], Config::get('TimeZone'))) .' (GMT '.Config::get('TimeZone').') - <b>IP: </b> '.$logrow['lg_ip'].'<br />';
        }

    } else {

        $row = array(
            'us_fullname'       => '',
            'us_username'       => '',
            'us_password'       => '',
            'us_password_confirm'   => '',
            'us_email'          => '',
            'us_address'        => '',
            'us_phone'          => '',
            'us_website'        => '',
            'us_enable'         => '1',
            'us_e2group'        => '0',
            'us_onlinecount'    => '0',
        );

    }

    extract($row);

    $us_password = '';
    $us_password_confirm = '';
}

$form = new Fete_View_Helper_Form();

$groupOptions = $form->selectAssoc('us_e2group', $groups, $us_e2group);

$enableOptions = $form->selectAssoc('us_enable', $privileges, $us_enable);

if ($id > 0 ) {
    $pageTitle = fl('pt_EditUser');
} else {
    $pageTitle = fl('pt_AddUser');
}